#include<stdio.h>
#include<errno.h>
#include<assert.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

#define NUM 128
#define NONE_FLUSH 0
#define LINE_FLUSH 1
#define FULL_FLUSH 2
typedef struct _myFILE 
{
  int _fileno;
  char _buffer[NUM];
  int _flags;
  int _end;
}_myFILE;
void my_fflush(_myFILE* fp)
{
  assert(fp);
  if(fp->_end>0)
  {
    write(fp->_fileno,fp->_buffer,fp->_end);
    fp->_end=0;
    syncfs(fp->_fileno);
  }
}
_myFILE* my_fopen(const char* filename,const char* method)
{
  assert(filename);
  assert(method);
  int flags=0;
  if(strcmp(method,"a")==0)
  {
    flags=O_WRONLY|O_CREAT|O_APPEND;
  }
  else if(strcmp(method,"w")==0)
  {
    flags=O_WRONLY|O_CREAT|O_TRUNC;
    
  }
  else if(strcmp(method,"r")==0)
  {

  }
  int fileno=open(filename,flags,0666);
  if(fileno<0)
  {
    perror("open");
    return NULL;
  }
  _myFILE* fp=(_myFILE*)malloc(sizeof(_myFILE));
  if(fp==NULL){ return fp;}
  memset(fp,0,sizeof(_myFILE));
  fp->_fileno=fileno;
  fp->_flags=LINE_FLUSH;  
  fp->_end=0;
  return fp;
}
void my_write(_myFILE* fp,const char* start,int len)
{
  assert(fp);
  assert(start);
  strncpy(fp->_buffer,start,len);
  fp->_end+=len;
  //printf("!!!!!!!");
  if(fp->_flags & NONE_FLUSH)
  {
    
  }
  else if(fp->_flags & LINE_FLUSH)
  {
   // printf("fp->_end-1:%d",fp->_end-1);
    if(fp->_buffer[fp->_end-1]=='\n')
    {
      //printf("!!!!!!!");
      write(fp->_fileno,fp->_buffer,fp->_end);
      fp->_end=0;
      syncfs(fp->_fileno);    
    }
  }
  else if(fp->_flags & FULL_FLUSH)
  {

  }
}
void my_fclose(_myFILE* fp)
{
  assert(fp);
  my_fflush(fp);
  close(fp->_fileno);
  free(fp);       //忘记
}
int main()    //第二个测试例子
{   
   _myFILE *fp = my_fopen("log.txt", "w");
    if(fp == NULL)
    {
        printf("my_fopen error\n");
        return 1;
    }

    const char *s = "-aaaaaaa++";
    my_write(fp, s, strlen(s));
    printf("写入了一个不满足刷新条件的字符串\n");
    fork();
 
    //模拟进程退出
    my_fclose(fp);
}
//int main()
//{
//  _myFILE* fp=my_fopen("log.txt","w");
//  if(fp==NULL)
//  {
//    perror("fopen");
//    return 1;
//  }
//  char arr[NUM]="hello linux!!!\n";
//  my_write(fp,arr,strlen(arr)); 
//  //printf("hello linux\n");
//  my_fclose(fp);
//  return 0;
//}

